/*
 * @Author: liuxiao
 * @Date: 2024-02-24 18:33:36
 * @Last Modified by: liuxiao
 * @Last Modified time: 2024-03-03 23:35:41
 * ps:全局异常处理
 */

import { Context, Next } from 'koa'
import { HttpException } from './HttpException'

const catchError = async (ctx: Context, next: Next) => {
  try {
    await next() // 下一个中间件函数
  } catch (error: any) {
    // 检查 error 是否为有效对象
    if (!error || typeof error !== 'object') {
      error = new Error('Unknown error')
    }

    if (error instanceof HttpException) {
      const responseBody = {
        result: error.result || null,
        msg: error.msg || '未知错误',
        errorCode: error.errorCode || 999,
        requestUrl: `${ctx.method} ${ctx.path}`,
        code: error.code || 1
      }
      ctx.body = responseBody
      ctx.response.status = error.statusCode || 500
    } else {
      const responseBody = {
        code: 1,
        msg: '服务器内部错误!',
        error_code: 999,
        requestUrl: `${ctx.method} ${ctx.path}`
      }
      ctx.body = responseBody
      ctx.status = 500

      // 记录非 HttpException 的错误日志（可选）,以后做日志的时候优化
      console.error('Unexpected server error:', error.message || error)
    }
  }
}

export default catchError
